#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#include <sys/time.h>

// 全局变量存储中间结果
typedef struct {
    double a, b, c;
    double discriminant;
    double root1, root2;
    int discriminant_computed;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} EquationSolver;

void* compute_discriminant(void* arg) {
    EquationSolver* solver = (EquationSolver*)arg;
    double a = solver->a, b = solver->b, c = solver->c;
    
    pthread_mutex_lock(&solver->mutex);
    solver->discriminant = b*b - 4*a*c;
    solver->discriminant_computed = 1;
    pthread_cond_signal(&solver->cond);
    pthread_mutex_unlock(&solver->mutex);
    
    return NULL;
}

void* compute_roots(void* arg) {
    EquationSolver* solver = (EquationSolver*)arg;
    
    pthread_mutex_lock(&solver->mutex);
    while (!solver->discriminant_computed) {
        pthread_cond_wait(&solver->cond, &solver->mutex);
    }
    
    double discriminant = solver->discriminant;
    double a = solver->a, b = solver->b;
    
    if (discriminant > 0) {
        solver->root1 = (-b + sqrt(discriminant)) / (2*a);
        solver->root2 = (-b - sqrt(discriminant)) / (2*a);
    } else if (discriminant == 0) {
        solver->root1 = solver->root2 = -b / (2*a);
    } else {
        double realPart = -b / (2*a);
        double imagPart = sqrt(-discriminant) / (2*a);
        printf("方程有复数解: %.2f + %.2fi 和 %.2f - %.2fi\n", 
               realPart, imagPart, realPart, imagPart);
        solver->root1 = solver->root2 = NAN;
    }
    
    pthread_mutex_unlock(&solver->mutex);
    return NULL;
}

int main() {
    EquationSolver solver;
    pthread_t thread1, thread2;
    struct timeval start, end;
    
    // 初始化
    pthread_mutex_init(&solver.mutex, NULL);
    pthread_cond_init(&solver.cond, NULL);
    solver.discriminant_computed = 0;
    
    printf("请输入一元二次方程的系数(a, b, c): ");
    scanf("%lf %lf %lf", &solver.a, &solver.b, &solver.c);
    
    gettimeofday(&start, NULL);
    
    // 创建线程计算判别式和根
    pthread_create(&thread1, NULL, compute_discriminant, &solver);
    pthread_create(&thread2, NULL, compute_roots, &solver);
    
    // 等待线程完成
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    
    gettimeofday(&end, NULL);
    
    // 计算执行时间(毫秒)
    long seconds = end.tv_sec - start.tv_sec;
    long microseconds = end.tv_usec - start.tv_usec;
    double elapsed = seconds * 1000.0 + microseconds / 1000.0;
    
    // 输出结果
    if (!isnan(solver.root1)) {
        printf("方程的解: x1 = %.2f, x2 = %.2f\n", solver.root1, solver.root2);
    }
    printf("计算耗时: %.3f 毫秒\n", elapsed);
    
    // 清理资源
    pthread_mutex_destroy(&solver.mutex);
    pthread_cond_destroy(&solver.cond);
    
    return 0;
}